<?php

namespace App\Services;

use App\Exceptions\ApiException;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;

class YouzanApiService extends Service
{
    protected $clientId;
    protected $clientSecret;
    protected $httpClient;
    protected $kdtId;
    protected $version;

    public function __construct()
    {
        $this->clientId = env('YOUZAN_CLIENT_ID');
        $this->clientSecret = env('YOUZAN_CLIENT_SECRET');
        $this->kdtId = intval(env('YOUZAN_KDT_ID'));
        $this->version = env('YOUZAN_API_VERSION');
        $this->httpClient = new Client(['base_uri' => 'https://open.youzan.com/api/oauthentry/']);
    }

    protected function getAccessToken()
    {
        return Cache::get('youzan_access_token', function () {
            $response = $this->httpClient->request('POST', 'https://open.youzan.com/oauth/token', [
                'form_params' => [
                    'client_id' => $this->clientId,
                    'client_secret' => $this->clientSecret,
                    'grant_type' => 'silent',
                    'kdt_id' => $this->kdtId
                ]
            ]);
            $response_contents = $response->getBody()->getContents();
            $response_data = json_decode($response_contents, true);
            if (isset($response_data['error'])) {
                throw new ApiException('YZ_error:' . $response_data['error_description'], intval($response_data['error']));
            }
            $access_token = $response_data['access_token'];
            $expires_in = intval($response_data['expires_in']) / 60;
            Cache::put('youzan_access_token', $access_token, $expires_in);
            return $access_token;
        });
    }

    /**
     * 处理请求返回。
     * @param $response \Psr\Http\Message\ResponseInterface
     * @param null $key
     * @return mixed
     */
    protected function getResponseData($response, $key = null)
    {
        $response_contents = $response->getBody()->getContents();
        $response_data = json_decode($response_contents, true);
        if (isset($response_data['error_response'])) {
            throw new ApiException($response_data['error_response']['msg'], $response_data['error_response']['code']);
        }
        if (!empty($key)) {
            return $response_data[$key];
        }
        return $response_data;
    }

    public function itemOnsale($pageSize = 40, $pageNo = 1, $query = '', $orderBy = '', $tagId = null, $updateTimeEnd = null, $updateTimeStart = null)
    {
        $form_params = [
            'access_token' => $this->getAccessToken(),
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecret,
            'kdt_id' => $this->kdtId,
            'page_size' => $pageSize,
            'page_no' => $pageNo,
            'q' => $query,
            'order_by' => $orderBy
        ];
        if ($tagId != null) {
            $form_params['tag_id'] = $tagId;
        }
        if ($updateTimeStart != null) {
            $form_params['update_time_start'] = $updateTimeStart;
        }
        if ($updateTimeEnd !== null) {
            $form_params['update_time_end'] = $updateTimeEnd;
        }
        $response = $this->httpClient->request('POST', 'youzan.items.onsale/' . $this->version . '/get', [
            'form_params' => $form_params
        ]);
        return $this->getResponseData($response, 'response');
    }
}